package cn.xiaobai.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.xiaobai.config.MysqlConfig;
import cn.xiaobai.domain.Message;
import cn.xiaobai.domain.User;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * 认证服务
 *
 * @Author yangdaji
 * @Date 2023/12/20
 * @PackageName cn.xiaobai.service
 * @ClassName AuthorServer
 */
public class AuthorServer {


    private static Logger log = Logger.getLogger(AuthorServer.class.getName());

    private static MysqlConfig mysqlConfig = MysqlConfig.getInstance();

    public Message checkConn() {
        Message message = new Message();
        if (mysqlConfig.getConn() != null) {
            message.setState(true);
        }else {
            message.setMsg("请检查当前 [ db.properties ] 文件是否正常");
            message.setState(false);
        }
        return message;
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public Message login(String username, String password) {
        Message message = new Message();
        if (checkAcc(username, password, HandlerType.LOGIN)) {
            message.setMsg("登录成功");
            message.setState(true);
        } else {
            message.setMsg("登录失败");
        }
        return message;
    }

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public Message regis(String username, String password) {
        Message message = new Message();
        if (checkAcc(username, password, HandlerType.REGIS)) {
            Connection conn = mysqlConfig.getConn();
            try {
                conn.setAutoCommit(false);
                String insertUser = "insert into user(username,password) values(?,?)";
                PreparedStatement preparedStatement = conn.prepareStatement(insertUser);
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, Base64.encode(password, StandardCharsets.UTF_8));
                preparedStatement.execute();
                conn.commit();
                message.setMsg("注册成功");
                message.setState(true);
                return message;
            } catch (SQLException e) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
                throw new RuntimeException(e);
            }
        }
        message.setMsg("注册失败");
        return message;
    }

    /**
     * 检查
     *
     * @param username
     * @param password
     * @return
     */
    public boolean checkAcc(String username, String password, HandlerType type) {

        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return false;
        }

        String queryName = "select username, password from user where username=?";
        Connection conn = mysqlConfig.getConn();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(queryName);
            preparedStatement.setString(1, username);

            ResultSet resultSet = preparedStatement.executeQuery();
            User user = null;
            while (resultSet.next()) {
                String queryUser = resultSet.getString("username");
                String queryPassword = resultSet.getString("password");
                user = new User(queryUser, queryPassword);
            }


            if (HandlerType.LOGIN.equals(type)) {
                if (user != null) {
                    // 验证密码
                    if (password.equals(Base64.decodeStr(user.getPassword(), StandardCharsets.UTF_8))) {
                        // 密码验证成功
                        return true;
                    }
                }
                log.warning("账户/密码错误!");
            } else {
                // 注册
                if (user == null) {
                    return true;
                } else {
                    log.warning(username + " 用户已注册");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    enum HandlerType {
        LOGIN,
        REGIS
    }


}
